//- Copyright (C) 2023 Beijing Huaxia Chunsong Technology Co., Ltd. 
//- <https://www.chatopera.com>, Licensed under the Chunsong Public 
//- License, Version 1.0  (the "License"), https://docs.cskefu.com/licenses/v1.html
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
//- Copyright (C) 2018-Jun. 2023 Chatopera Inc, <https://www.chatopera.com>
//- Licensed under the Apache License, Version 2.0
//- http://www.apache.org/licenses/LICENSE-2.0
- var schemaFixed = schema ? schema : 'http'
- var portFixed = schemaFixed == "https" ? 443 : port
- var baseUrl = schemaFixed +'://' + hostname + ':' + portFixed

- var style = 'text-align:center;height: 150px;border-radius: 30px;width: 40px;margin: 0px 5px 0 0; float:left ; word-wrap: break-word;overflow: hidden;font-size:15px;color:#FFFFFF;text-align: center;padding-top: 15px;border: 1px solid #DCDCDC;background-color:#008df3;';
if inviteData.consult_vsitorbtn_model == "2"
    - style = 'height: 70px;border-radius: 3px; width: 70px;margin: 40px auto;word-wrap:break-word;overflow:hidden;font-size: 22px;color:#FFFFFF;text-align:center;padding-top:10px;border: 1px solid #DCDCDC;background-color:#dddddd;'
else if inviteData.consult_vsitorbtn_model == "3"
    - style = 'height: 70px;border-radius: 70px; width: 70px;margin: 40px auto;word-wrap:break-word;overflow:hidden;font-size: 22px;color:#FFFFFF;text-align:center;padding-top:5px;border: 1px solid #DCDCDC;background-color:#dddddd;'

- var text = 'width:25px;'
if inviteData.consult_vsitorbtn_model == "2"
    - text = 'width:100%;'
else if inviteData.consult_vsitorbtn_model == "3"
    - text = 'width:100%;'

- var theme = 'background-color: #377FED !important;border-color: #377FED !important;'
if inviteData.consult_vsitorbtn_color == "2"
    -  theme = 'background-color: #67CAFF !important;'
else if  inviteData.consult_vsitorbtn_color == "3"
    - theme = 'background-color: #8E8E8E !important;'
else if inviteData.consult_vsitorbtn_color == "4"
    - theme = 'background-color: #32c24d !important;'
else if inviteData.consult_vsitorbtn_color == "5"
    - theme = 'background-color: #E45DB3 !important;'
else if inviteData.consult_vsitorbtn_color == "6"
    - theme = 'background-color: #FF626F !important;'

- var position = "right:10px;top:40%;"
if inviteData.consult_vsitorbtn_position == "right,top"
    - position = "right:10px;top:10px;"
else if  inviteData.consult_vsitorbtn_position == "right,bottom"
    - position = "right:10px;bottom:10px;"
else if  inviteData.consult_vsitorbtn_position == "right,middle"
    - position = "right:10px;top:40%;"
else if  inviteData.consult_vsitorbtn_position == "left,top"
    - position = "left:10px;top:10px;"
else if  inviteData.consult_vsitorbtn_position == "left,middle"
    - position = "left:10px;top:40%;"
else if  inviteData.consult_vsitorbtn_position == "left,bottom"
    -sition = "left:10px;bottom:10px;"

- var invitetheme = 'background-color: #377FED !important;'
if  inviteData.consult_invite_color == "2"
    - invitetheme = 'background-color: #67CAFF !important;'
else if  inviteData.consult_invite_color == "3"
    - invitetheme = 'background-color: #8E8E8E !important;'
else if  inviteData.consult_invite_color == "4"
    - invitetheme = 'background-color: #32c24d !important;'
else if  inviteData.consult_invite_color == "5"
    - invitetheme = 'background-color: #E45DB3 !important;'
else if  inviteData.consult_invite_color == "6"
    - invitetheme = 'background-color: #FF626F !important;'

#ukefu-point.ukefu-im-point(draggable="true", style='display:none;z-index:100000;font-family:14px \\5FAE\\8F6F\\96C5\\9ED1,Helvetica Neue,Helvetica,PingFang SC,Tahoma,Arial,sans-serif;position: fixed;' + position + (inviteData.skill == true && inviteData.consult_skill_fixed == false ? 'cursor:default;' : 'cursor: pointer;'))
    #ukefu-point-theme.ukefu-theme-color.theme1(class="ukefu-point-theme" + (inviteData.consult_vsitorbtn_model ? inviteData.consult_vsitorbtn_model : '1'), style=style + theme)
        #ukefu-im-point-text.ukefu-im-point-text(style='cursor: pointer;' + text + ';line-height: 23px;font-size: 15px;text-align: center;margin: 0 auto;')
            i(style="width:24px;height:24px;display: inline-block;font: normal normal normal 14px/1 FontAwesome;font-size: inherit;text-rendering: auto;-webkit-font-smoothing: antialiased;background-image:url();")
            | #{inviteData.consult_vsitorbtn_content ? inviteData.consult_vsitorbtn_content : '在线客服'}
    if inviteData.skill == true && inviteData.consult_skill_fixed == false
        #ichatContent.ichat-content.ichat-float-left(style='width:152px;display: block;font-size:14px;' + theme + ';box-shadow: 0 0 10px #DDDDDD;border: 1px solid #DDDDDD;overflow: hidden;text-align: left;')
            .ichat-title.ichat-cursor(style='color: #FFFFFF;font-weight:400;font-size: 14px;font-weight: 400;height: 28px;line-height: 28px;overflow: hidden;padding: 0 5px;background-repeat: repeat-x;')
                img(src=baseUrl + '/images/logo-icon.png',style='height:20px;vertical-align: middle;')
                | #{inviteData.consult_skill_title}
            #ichatItem0.ichat-list(style='background: none repeat scroll 0 0 #FFFFFF;overflow-x: hidden;overflow-y: auto;padding: 5px 0;margin: 0;')
                if pointAd
                    if pointAd.adtype == "image"
                        a(href=pointAd.url, title=pointAd.tiptext, target="_blank")
                            img(src=baseUrl + pointAd.imgurl, style='max-width:140px;max-height:90px;margin:0 5px;vertical-align: middle;')
                    else
                        // 文本
                        for ad in pointAds
                            - var pointAdsNum = 0
                            if ad.adtype == "text" && pointAdsNum <= 5
                                - pointAdsNum = pointAdsNum + 1
                                div(style="padding:0px 5px 10px 5px;border-bottom:1px solid #dedede;")
                                    a#point_ad_text(href=ad.url, title=ad.tiptext, target="_blank")= ad.content
                else
                    img(src=baseUrl + '/images/title.jpg', style='width:140px;margin:0 5px;vertical-align: middle;')
                div(style="padding:10px 5px;text-align:center;color:#555;")= inviteData.skill == true && inviteData.consult_skill_fixed == false && inviteData.consult_skill_msg ? inviteData.consult_skill_msg : ''
          
                if skillGroups
                    for skill in skillGroups
                        - var skillNum = 0
                        for agent in agentList
                            if agent.skills[skill.id]
                                - skillNum = skillNum + 1
            
                        div(style='padding:5px;color:#555;border:1px solid #dddddd;background-color:#efefef;')
                            a(href=baseUrl + '/im/text/' + appid + '.html?skill=' + skill.id, onclick='return openAgentChatDialog(this.href)', style='color: #777;    text-decoration: none;') #{skill.name}（#{skillNum}）

                        if inviteData.consult_skill_agent && inviteData.consult_skill_agent == true
                            ul(class="ichat-list-ul", style="border: 0 none;list-style: none outside none;margin: 0;padding: 0;width: 150px;")
                                if agentList
                                    - var agentNum = 0
                                    for agent in agentList
                                        if agent.organ && agent.organ == skill.id && agentNum < inviteData.consult_skill_maxagent
                                            - agentNum = agentNum + 1
                                            li(style="height: 23px;list-style: none outside none;margin-left: 6px;overflow: hidden;padding: 2px;")
                                                a(href=baseUrl + '/im/text/' + appid + '.html?skill=' + skill.id + '&agent=' + agent.id, onclick='return openAgentChatDialog(this.href)', style='color: #777;    text-decoration: none;')
                                                    img(src=baseUrl + '/images/creater.png', style='vertical-align: middle;')
                                                    | #{agent.uname}
                else if inviteData.onlyareaskill && inviteData.areaskilltipmsg
                    div(style="padding:10px 5px;text-align:center;color:#555;border-top:1px solid #dedede;")= inviteData.areaskilltipmsg
            div(class="ichat-title ichat-cursor", style="color: #FFFFFF;font-weight:400;font-size: 14px;font-weight: 400;height: 28px;line-height: 28px;overflow: hidden;padding: 0 5px;background-repeat: repeat-x;text-align:right;")= inviteData.consult_skill_bottomtitle

#ukefu-invite-dialog.ukefu-im-preview(style="z-index: 2147483648;display:none;height:177px;position: fixed;z-index:10000;border-radius: 2px;padding: 0px;overflow: hidden;margin: 0px;" + invitetheme)
    #ukefu-cousult-invite-dialog.ukefu-im-preview-bar.ukefu-cousult-invite-dialog.ukefu-theme-color.theme1(style="padding:0px;height:100%;width:100%;background-size: cover;background:url(" + baseUrl + '/res/image.html?id=' + inviteData.consult_invite_bg + ') no-repeat')
        a(href="javascript:void(0)", onclick="cskefu.refuseInvite();")
            span(style="float: right;width: 20px;height: 20px;color: #ffffff;font-size: 20px;") ×
        #ukefu_consult_body.ukefu-consult-body(style='width:100%;height:100%;')
            #ukefu-cousult-invite-content(class="ukefu-cousult-invite-content", style="color: #FFFFFF;width: 70%;height: 70px;line-height: 35px;font-size: 13pt;font-weight: 200;word-wrap: break-word;word-break: break-all;position: absolute;top: 30px;left: 25%;")= inviteData.consult_invite_content ? inviteData.consult_invite_content : '欢迎来到本网站，请问有什么可以帮您？'
        .ukefu-cousult-invite-btn(style='position: absolute;bottom: 0px;right: 0px;margin: 0px 10px 10px 0px;')
            button#invite-btn.theme1(style='border-color:#FFFFFF !important;color:#FFFFFF;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;background-color: #009688;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;margin-right:10px;border: none;border-radius: 2px;cursor: pointer;opacity: .9;filter: alpha(opacity=90);border:1px solid #FFFFFF;' + invitetheme, onclick='cskefu.refuseInvite();')= inviteData.consult_invite_later ? inviteData.consult_invite_later : '稍后再说'
            button(class="", style="display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;background-color: #009688;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;border: none;border-radius: 2px;cursor: pointer;opacity: .9;filter: alpha(opacity=90);background-color:#FFFFFF;color:#333333;", onclick="openInviteChatDialog();")= inviteData.consult_invite_accept ? inviteData.consult_invite_accept : '现在咨询'

script(type='text/javascript')
    include fingerprint.js
    include qs.min.js

script(type='text/javascript').
    var genUrl = function (subPath, query) {
        return '!{baseUrl}/im/' + subPath + '?' + Qs.stringify(query);
    };

    var data = {};
    var cskefuOnlineUserId;

    function ajax(options) {
        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || 'json';
        options.async = options.async || true;
        var params = getParams(options.data);
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP')
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        };
        if (options.type == 'GET') {
            xhr.open("GET", options.url + '?' + params, options.async);
            xhr.send(null)
        } else if (options.type == 'POST') {
            xhr.open('POST', options.url, options.async);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        }
    }

    function getParams(data) {
        var arr = [];
        for (var param in data) {
            arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
        }
        arr.push(('randomNumber=' + Math.random()).replace('.'));
        return arr.join('&');
    }

    var protocol = "#{schema}"

    document.cookie = ""

    var signal = 0;
    function append(parent, text) {
        if (typeof text === 'string') {
            var temp = document.createElement('div');
            temp.innerHTML = text;
            parent.appendChild(temp);
        } else {
            parent.appendChild(text);
        }
    }
    function closerefresh() {
        location.reload();
    }

    var appid = '#{appid}';
    var client = '#{client}';

    var cskefu = {
        service: {agentno: null},
        time: new Date().getTime(),
        in: genUrl(appid + '/userlist.html', {
            appid: appid,
            aiid: '#{aiid}',
            client: client,
        }),
        url: genUrl('online', {
            appid: appid,
            client: client,
            aiid: '#{aiid}',
        }),
        chat: genUrl('index.html', {
            appid: appid,
            client: client,
            aiid: '#{aiid}',
        }),
        refuse: genUrl('refuse.html', {
            appid: appid,
            client: client,
            aiid: '#{aiid}',
        }),
        config: function (d) {
            data = d;
            if (d.id != null && d.id != '') {
                cskefuOnlineUserId = d.id;
            }
        },
        ajax: function (url, success, error) {
            var xhr = false;
            signal = signal + 1;
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+（IE7.0及以上）
            } catch (e) {
                try {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6（IE5/6）
                } catch (e2) {
                    xhr = false;
                }
            }
            if (!xhr && typeof XMLHttpRequest != 'undefined') {// Firefox, Opera 8.0+, Safari
                xhr = new XMLHttpRequest();
            }
            xhr.onreadystatechange = function (data) {
                if (xhr.readyState == 4) {
                    var status = xhr.status;
                    if (status >= 200 && status < 300) {
                        var event = xhr.responseText;
                        if (event && event.indexOf('invite') >= 0) {
                            var agentno = event.substring(event.lastIndexOf(":") + 1).trim();
                            cskefu.service.agentno = agentno;
                            cskefu.writeinvite();
                        } else if (event && event.indexOf('refuse') >= 0) {
                            cskefu.refuseInvite();
                        } else if (event && event.indexOf('accept') >= 0) {
                            cskefu.acceptInvite();
                        }
                        if (success) {
                            success(event);
                        }
                    } else {
                        //
                        if (error) {
                            error();
                        }
                    }
                    xhr.abort();
                    signal = signal - 1;
                }
            }
            xhr.open("GET", url, true);

            try {
                xhr.send(null);
            } catch (e) {
            }
        },
        ping: function () {
            var url = cskefu.url;
            if (data) {
                if (data.id) {
                    url = url + "&id=" + data.id;
                }
                if (data.name) {
                    url = url + "&name=" + encodeURIComponent(data.name);
                }
                if (data.email) {
                    url = url + "&email=" + encodeURIComponent(data.email);
                }
                if (data.phone) {
                    url = url + "&phone=" + encodeURIComponent(data.phone);
                }
                url = url + "&title=" + encodeURIComponent(document.title);
                if ('traceid') {
                    url = url + "&traceid=#{traceid}"
                }

                url = url + "&url=" + encodeURIComponent(location.href)
            }
            cskefu.ajax(url + "&userid=" + cskefuOnlineUserId + "&sessionid=#{sessionid}&sign=" + cskefuOnlineUserId + "&t=" + new Date().getTime(), function () {
                cskefu.ping();
            });
        },
        writepoint: function () {
            var ukefuInviteDialog = document.getElementById("ukefu-invite-dialog");
            if (#{phone == true}) {
                ukefuInviteDialog.style.bottom = "0px"
                ukefuInviteDialog.style.width = "100%"
            } else {
                var height = document.documentElement.clientHeight;
                var width = document.documentElement.clientWidth;
                var top = (50 - 92 * 100 / height) + "%";
                var left = (50 - 210 * 100 / width) + "%";

                ukefuInviteDialog.style.top = top
                ukefuInviteDialog.style.width = "420px"
                ukefuInviteDialog.style.left = left
            }

            if (#{inviteData.skill == true && inviteData.consult_skill_fixed == false}) {
                document.getElementById("ukefu-im-point-text").onclick = function () {
                    if (document.getElementById("ichatContent").style.display == "none") {
                        document.getElementById("ichatContent").style.display = 'block';
                    } else {
                        document.getElementById("ichatContent").style.display = 'none';
                    }
                }
            } else {
                document.getElementById("ukefu-point").onclick = function () {
                    cskefu.openChatDialog();
                }
                document.getElementById("ukefu-point").ondragend=function(e){
                    let div = e.target || window.event;
                    var style = {
                        position: "absolute",
                        left: "0",
                        top: "0"
                    };
                    for(var k in style){
                        div.style[k] = style[k];
                    }
                    div.style.left = e.clientX + "px";
                    div.style.top = e.clientY - 150 +  "px";
                }
            }
            var inviteDialog = document.getElementById('ukefu-invite-dialog');
            if (#{phone && mobile == true})
                inviteDialog.style.bottom = 0;
            else {
                var height = document.documentElement.clientHeight;
                var width = document.documentElement.clientWidth;
                var top = (50 - 92 * 100 / height) + "%";
                var left = (50 - 210 * 100 / width) + "%";

                inviteDialog.style.top = top;
                inviteDialog.style.left = left;
            }

            if (#{!!inviteAd}) {
                var inviteAdHtml = "!{inviteAd.adtype == "image" ? "<a href='" + inviteAd.url + "' title='" + inviteAd.tiptext + "' target='_blank'><img src='" + baseUrl + inviteAd.imgurl + "' style='max-width:420px;max-height:178px;margin:0px;vertical-align: middle;'/></a>" : "<div style='padding:0px 5px 10px 5px;border-bottom:1px solid #dedede;'><a href='" + inviteAd.url + "' title='" + inviteAd.tiptext + "' target='_blank' id='point_ad_text'>" + inviteAd.content + "</a></div>"}";

                var inviteBody = document.getElementById('ukefu_consult_body');
                if (inviteBody) {
                    inviteBody.innerHTML = inviteAdHtml;
                }
            }
        },
        openChatDialog: function () {
            cskefu.openChatDialogWithURL(cskefu.chat);
        },
        openChatDialogWithURL: function (url) {
            url = url + "&userid=" + cskefuOnlineUserId + "&sessionid=#{sessionid}"
            if (data) {
                if (data.id) {
                    url = url + "&id=" + data.id;
                }
                if (data.name) {
                    url = url + "&name=" + encodeURIComponent(data.name);
                }
                if (data.email) {
                    url = url + "&email=" + encodeURIComponent(data.email);
                }
                if (data.phone) {
                    url = url + "&phone=" + encodeURIComponent(data.phone);
                }
            }

            if (#{inviteData.skill == true && inviteData.consult_skill_fixed == true})
                url = url + "&skill=#{inviteData.consult_skill_fixed_id}";

            url = url + "&title=" + encodeURIComponent(document.title);
            if (#{!!traceid})
                url = url + "&traceid=#{traceid}"

            url = url + "&url=" + encodeURIComponent(location.href);
            try {
                window.open(url + "&t=" + new Date().getTime(), "ukefu-chat", "height=600, width=850, top=" + (window.screen.availHeight - 30 - 600) / 2 + ", left=" + (window.screen.availWidth - 10 - 750) / 2 + ",toolbar=no, menubar=no, scrollbars=no, resizable=no, directories=no,location=no, status=no");
            } catch (e) {
            }
            return false;
        },
        display: function () {
            // 注入聊天控件按钮，默认不展示
            cskefu.writepoint();

            // 显示聊天控件按钮
            var isDisplayDelay = #{(inviteData.consult_vsitorbtn_delay && inviteData.consult_vsitorbtn_delay > 0)}
            var displayDelay = 0;
            if (isDisplayDelay){
                displayDelay = #{inviteData.consult_vsitorbtn_delay}
            }
            setTimeout(function (){
                // 入口样式：无，consult_vsitorbtn_model = 9
                if (#{inviteData && inviteData.consult_vsitorbtn_model != '9' && inviteData.whitelist_mode == false}) {
                    // 设置为展示对话按钮
                    document.getElementById("ukefu-point").style.display = "block";
                }
            }, displayDelay); //延时显示 访客入口

           // 显示邀请弹窗
           if (#{inviteData.consult_invite_enable}) {
                if (#{inviteData.consult_invite_delay && inviteData.consult_invite_delay > 0}) {
                    setTimeout(function () {
                        cskefu.writeinvite();
                    }, !{inviteData.consult_invite_delay});
                } else {
                        cskefu.writeinvite();
                }
           }
        },
        writeinvite: function () {
            document.getElementById('ukefu-invite-dialog').style.display = "block";
        }
        ,
        refuseInvite: function () {
            document.getElementById('ukefu-invite-dialog').style.display = "none";
            cskefu.ajax(cskefu.refuse + "&userid=" + cskefuOnlineUserId + "&sessionid=#{sessionid}&t=" + new Date().getTime());
        }
        ,
        acceptInvite: function () {
            document.getElementById('ukefu-invite-dialog').style.display = "none";
        }
        ,
        check: function () {
            var checkTimes = 0;
            setInterval(function () {
                if (signal <= 0) {
                    checkTimes++;
                } else {
                    checkTimes = 0;
                }
                if (checkTimes >= 3) {    //检查当前的 Keep-Alive是否存活，检查3次都处于未存活状态，则启动
                    //
                    signal = 0;
                    checkTimes = 0;
                    cskefu.ping();
                    console.log("春松客服客户端信息校对");
                }
            }, 5000);
        }

    }

    // 邀请聊天
    function openInviteChatDialog() {
        var url = cskefu.chat + "&agent=" + cskefu.service.agentno + "&isInvite=true";
        return cskefu.openChatDialogWithURL(url);
    }

    // 技能组或坐席聊天
    function openAgentChatDialog(url) {
        return cskefu.openChatDialogWithURL(url);
    }

    if (#{webimexist == true}) {
        Fingerprint2.get({
            extraComponents: [
                {
                    key: "cskefuAppId",
                    getData: function (done, options) {
                        done("#{appid}")
                    }
                },
                {
                    key: "rndId",
                    getData(done, options) {
                        var rnd = '';
                        if (localStorage) {
                            rnd = localStorage.finger;
                            if (!rnd) {
                                rnd = Math.random();
                                localStorage.finger = rnd;
                            }
                        }

                        done(rnd);
                    }
                }
            ]
        }, function (components) {
            var glue = components.map(function (component) {
                return component.value
            })
            cskefuOnlineUserId = Fingerprint2.x64hash128(glue.join(''), 31);
            cskefu.ajax(cskefu.in + "&userid=" + cskefuOnlineUserId + "&t=" + new Date().getTime(), function (data) {
                if (data == "in") {
                } else {
                    cskefu.display();
                    cskefu.ping();
                    cskefu.check();
                }
            });
        });
    }















